<?php
namespace Mouta\UserBundle\Mailer;

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\Routing\RouterInterface;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Mailer\MailerInterface;


class Mailer implements MailerInterface
{
	protected $mailer;
    protected $router;
    protected $templating;
    protected $parameters;

    public function __construct($mailer, RouterInterface $router, EngineInterface $templating, array $parameters)
    {
        $this->mailer = $mailer;
        $this->router = $router;
        $this->templating = $templating;
        $this->parameters = $parameters;
    }
	
    public function sendConfirmationEmailMessage(UserInterface $user)
    {
        $url = $this->router->generate('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), true);
        $rendered = $this->templating->render('UserBundle:Emails:registration.html.twig', array(
            'user' => $user,
            'confirmationUrl' =>  $url
        ));
		
		$subject = "";
		if($user->getSexo())
		{
			$subject = "Bienvenida ";
		} else {
			$subject = "Bienvenido ";
		}
		$subject .= $user->getNombre();
		
        $this->sendEmailMessage($rendered, $subject, $this->parameters['from_email']['confirmation'], $user->getEmail());
    }

    public function sendResettingEmailMessage(UserInterface $user)
    {
        $url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()), true);
        $rendered = $this->templating->render('UserBundle:Emails:reset.html.twig', array(
            'user' => $user,
            'confirmationUrl' => $url
        ));
        $this->sendEmailMessage($rendered,'Datos de acceso en Amistate', $this->parameters['from_email']['resetting'], $user->getEmail());
    }
	
	/**
     * @param string $renderedTemplate
     * @param string $fromEmail
     * @param string $toEmail
     */
    protected function sendEmailMessage($body, $subject, $fromEmail, $toEmail)
    {
        $message = \Swift_Message::newInstance();
		$cid1 = $message->embed(\Swift_Image::fromPath( realpath( __DIR__ . '/../../AmistateBundle/Resources/public/images/logo.png') ) );
		$cid2 = $message->embed(\Swift_Image::fromPath( realpath( __DIR__ . '/../../AmistateBundle/Resources/public/images/like-glyph.png') ) );
		
		$body = str_replace(array('[[cid1]]','[[cid2]]'), array($cid1,$cid2), $body);
		
        $message->setSubject($subject)
				->setFrom($fromEmail)
				->setTo($toEmail)
				->setBody($body)
				->setContentType('text/html');
		

        $this->mailer->send($message);
    }
}
